package com.alibaba.design.objectpoolpattern;

import java.util.ArrayList;

/**
 * @author zhouyanxiang
 * @create 2020-07-2020/7/31-19:12
 */
public class PoolManager {
    //连接池对象
    public static class PoolItem {
        boolean inUse = false;
        Object item; //池数据

        PoolItem(Object item) {
            this.item = item;
        }
    }
    //连接池集合
    private ArrayList items = new ArrayList();

    public void add(Object item) {
        this.items.add(new PoolItem(item));
    }

    static class EmptyPoolException extends Exception {

    }

    public Object get() throws EmptyPoolException {
        for (int i = 0; i < items.size(); i++) {
            PoolItem pitem = (PoolItem) items.get(i);
            if (pitem.inUse == false) {
                pitem.inUse = true;
                System.out.println("获取连接资源为： " + items.get(i));
                return pitem.item;
            }
        }
        throw new EmptyPoolException();
        // return null;
    }
    /**
     * 释放连接
     * @param item
     */
    public void release(Object item) {
        for (int i = 0; i < items.size(); i++) {
            PoolItem pitem = (PoolItem) items.get(i);
            if (item == pitem.item) {
                pitem.inUse = false;
                System.out.println("释放连接资源 ： " + items.get(i));
                return;
            }
        }
        throw new RuntimeException(item + " not null");
    }

}
